/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.wlhy.verifycode;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @BelongsPackage: org.jeecg.modules.wlhy.verifycode
 * @Author: duanlikao
 * @CreateTime: 2022-11-11 09:16
 * @Description:
 * @Version: 1.0
 */
@Api(tags="手机验证码")
@RestController
@RequestMapping("/verifycode")
public class VerifyCodeController {

    @Autowired
    private RedisUtil redisUtil;

    @AutoLog("获取手机验证码")
    @GetMapping(value = "/list")
    public Result<?> codeList(@RequestParam(name="phone",required=false,defaultValue = "") String phone ) {

        List<Map> codeList = new ArrayList<>();
        if(StringUtils.isNotEmpty(phone) ){
            if ( phone.length() != 11) {
                return Result.error ("手机号应为11位数。");
            }
            if ( !phone.matches(CommonConstant.REGEX_MOBILE)) {
                return Result.error("手机号格式错误！");
            }
            String code = redisUtil.hasKey(phone) ? String.valueOf(redisUtil.get(phone)) : StringUtils.EMPTY;
            if(StringUtils.isNotEmpty(code)){
                Map<String, String> codeListMaps = new HashMap<>();
                codeListMaps.put("phone",phone);
                codeListMaps.put("code",code);
                codeList.add(codeListMaps);
            }
        }else {
            Set<String> keys = redisUtil.keys("1*");
            for (String key : keys) {
                if ( key.length() != 11) {
                    continue;
                }
                if ( !key.matches(CommonConstant.REGEX_MOBILE)) {
                    continue;
                }
                Object value = redisUtil.get(key);
                if(value != null){
                    Map<String, String> codeListMaps1 = new HashMap<>();
                    codeListMaps1.put("phone",key);
                    codeListMaps1.put("code",value.toString());
                    codeList.add(codeListMaps1);
                }
            }
        }
        IPage<Map> pageList = new Page<>();
        pageList.setRecords(codeList);
        return Result.OK(pageList);
    }
}
